import {
  reactive,
  ref
} from 'vue'
import {
  onLoad,
  onShow
} from "@dcloudio/uni-app";
/**
 * 
 * @param {*} getList 获取列表数据接口
 * @param {*} options 
 *             limit 一页请求数据量
 *             showRefresh 页面每次show是否重新数据 
 * @returns 
 */
export const useList = (getList, options = {
  limit: 10,
  showRefresh: true,
}) => {
  const params = reactive({
    page: 1,
    limit: options.limit,
    total: 0
  })
  const orderList = ref([])
  onShow(async () => {
    if (!options.showRefresh && orderList.value.length !== 0) return
    params.page = 1
    const {
      list,
      total
    } = await getList({
      page: params.page,
      limit: params.limit
    })
    orderList.value = list
    params.total = total
  })
  // 获取更多数据
  const getMore = async () => {
    if (params.page * params.limit >= params.total) return
    params.page += 1
    const {
      list,
      total
    } = await getList({
      page: params.page,
      limit: params.limit
    })
    orderList.value = orderList.value.concat(list)
    params.total = total
  }
  // 刷新数据
  const resetList = async () => {
    params.page = 1
    const {
      list,
      total
    } = await getList({
      page: params.page,
      limit: params.limit
    })
    orderList.value = list
    params.total = total
  }
  return {
    orderList,
    getMore,
    resetList
  }
}